package com.cskaoyan.controller.wx;

import com.cskaoyan.bean.BaseData;
import com.cskaoyan.bean.BaseParam;
import com.cskaoyan.bean.BaseRespVo;
import com.cskaoyan.bean.user.Address;
import com.cskaoyan.bean.user.User;
import com.cskaoyan.service.AddressService;
import com.cskaoyan.service.UserService;
import com.sun.javafx.collections.MappingChange;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.yaml.snakeyaml.events.Event;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("wx/address")
public class WXAddressController {


    @Autowired
    UserService userService;
    @Autowired
    AddressService addressService;


    @RequestMapping("list")
    public BaseRespVo list() {
        //shiro 获取当前用户id
        Subject subject = SecurityUtils.getSubject();
        String username = (String) subject.getPrincipals().getPrimaryPrincipal();
        User user = userService.getUser(username);
        BaseData<Address> data = addressService.list(user.getId());
        return BaseRespVo.ok(data);
    }


    @RequestMapping("detail")
    public BaseRespVo detail(int id) {
        Address detail = addressService.detail(id);
        return BaseRespVo.ok(detail);
    }

    @PostMapping("save")
    public BaseRespVo save(@RequestBody Address address) {
        int saveAddressId;
        //shiro 获取当前用户id
        Subject subject = SecurityUtils.getSubject();
        String username = (String) subject.getPrincipals().getPrimaryPrincipal();
        User user = userService.getUser(username);
        int userId = user.getId();
        if (address.getId()== 0){
            saveAddressId  = addressService.saveAdd(address,userId);
        }else saveAddressId = addressService.saveUpdate(address);
        return BaseRespVo.ok(saveAddressId);
    }


    @PostMapping("delete")
    public BaseRespVo delete(@RequestBody Map map){
        //map ---<key - value>
          int num = addressService.delete((Integer) map.get("id"));
          if ( num == 0){
              return  BaseRespVo.fail("删除失败");
          }
        return BaseRespVo.ok();
    }
}
